import fs from 'fs'
import path from 'path'
import _ from 'lodash'

export const writeHtml = (id: string, type: string, html: string) => {
  const root = process.cwd()
  const url = `${root}/html/${type}/${id}.html`
  const dir = path.dirname(url)
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true })
  }
  fs.writeFileSync(url, html, 'utf-8')
}

export const writeJson = (name: string, json: string) => {
  const root = process.cwd()
  const url = `${root}/json/${name}.json`
  const dir = path.dirname(url)
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true })
  }
  fs.writeFileSync(url, json, 'utf-8')
}

export const readJson = (name: string) => {
  const root = process.cwd()
  const filePath = `${root}/json/${name}.json`
  if (fs.existsSync(filePath)) {
    return fs.readFileSync(filePath, 'utf-8')
  } else {
    throw new Error('该文件不存在')
  }
}

export const readHtml = (id: string, type: string) => {
  const root = process.cwd()
  const filePath = `${root}/html/${type}/${id}.html`
  
  if (fs.existsSync(filePath)) {
    return fs.readFileSync(filePath, 'utf-8')
  } else {
    throw new Error('该文件不存在')
  }
}

export const lastChar = (str: string) => {
  const L = str[str.length - 1]
  if (L === '；' || L === ';' || L === '。') {
    str = str.substring(0, str.length - 1)
  }
  return str
}

export const strip = (k: any) => {
  if (k == null) {
    return undefined
  }
  k = k.trim()
  k = k.replace('\n', '')
  k = k.replace('展开', '')
  k = k.replace(/\s/g, '')
  k = k.replace('【', '')
  k = k.replace('】', '')
  k = lastChar(k)
  return k
}

export const filterArr = (arr: any) => {
  if (!_.isArray(arr)) {
    return []
  }
  return arr.map((k: any) => {
    return strip(k)
  }).filter((k: any) => k)
}

export const joinArr = (target: any, opt = ',') => {
  if (target == null) {
    return undefined
  }
  if (!_.isArray(target)) {
    target = [target]
  }
  return filterArr(target).join(opt)
}